package logic

import (
	"context"
	"errors"
	"houses_srv/models"
	"houses_srv/pkg"

	"houses_srv/houses"
	"houses_srv/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddRealNameLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddRealNameLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddRealNameLogic {
	return &AddRealNameLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddRealNameLogic) AddRealName(in *houses.AddRealNameRequest) (*houses.AddRealNameResponse, error) {
	// todo: add your logic here and delete this line
	var err error
	var a models.AuthRealName
	a.UserId = int(in.UserId)
	err = a.ShowRealNameByUserId()
	if err != nil {
		logx.Error("实名失败", err)
		return nil, err
	}

	if a.ID != 0 {
		logx.Error("实名失败", errors.New("用户已实名"))
		return nil, errors.New("用户已实名")
	} else {
		if pkg.AuthRealName(in.IdCard, in.RealName) == false {
			logx.Error("实名失败", errors.New("第三方接口验证失败"))
			return nil, errors.New("第三方接口验证失败")
		}

		a.RealName = in.RealName
		a.IdCard = in.IdCard
		err = a.AddAuthRealName()
		if err != nil {
			logx.Error("实名失败", err)
			return nil, err
		}
	}

	return &houses.AddRealNameResponse{AuthRealNameId: int64(a.ID)}, nil
}
